/** 验证插件 */
(function($)
{
	/**
	 * 根据 validateProxy 属性 链式调用
	 */
	$.fn.Validater = function(options)
	{
		var isValid = true;
		this.each(function()
		{
			var validateProxy = $(this).attr("validateProxy");

			var value = $(this).QuickField("getData");
			var label = $(this).attr("label");
			var config = {
				label : label
			};
			var validateFailMsg = "";

			if (!StringUtils.isEmpty(validateProxy))
			{
				var proxyAry = validateProxy.split(" ");
				var flag = true;
				var _this = $(this);
				$.each(proxyAry, function(index, name)
				{
					var func = $.fn.QuickValidate.method[name];
					var result = "";
					if (func)
					{
						result = func(value, config);
					} else
					{
						func = eval(name);
						result = func.apply(_this, [ value, config ]);
						if (!StringUtils.isEmpty(result))
						{
							flag = false;
						}
					}
					if (!StringUtils.isEmpty(result))
					{
						flag = false;
						if (StringUtils.isEmpty(validateFailMsg))
						{
							validateFailMsg = result;
						}
					}
					return flag;
				})
				isValid = flag;
				if (!flag)
				{
					$.QuickAlert.alertFail({
						content : validateFailMsg,
						callback : function()
						{
							$(_this).focus();
						}
					});
				}
			}
			return flag;
		})
		return isValid;
	}

	$.fn.QuickValidate.method = {
		/** 字符串非空 */
		notNull : function(value, config)
		{
			var result = "";
			if (StringUtils.isEmpty(value))
			{
				result = config["label"] + "不能为空";
			}
			return result;
		}
		/** 长度校验 */
		,
		length : function(value, config)
		{
			var result = "";
			var len = StringUtils.getRealLength(value);
			var length = config["length"];
			var ary = length.split("-");
			if (ary.length == 1)
			{
				if (len > ary[0])
				{
					result = config["label"] + "最大长度为" + ary[0] + "个字符";
				}
			} else if (len < ary[0] || len > ary[1])
			{
				if (ary[0] == ary[1])
				{
					result = config["label"] + "的长度应为" + ary[0] + "个字符";
				} else
				{
					result = config["label"] + "的长度应在" + ary[0] + "-" + ary[1] + "之间";
				}
			}
			return result;
		}
		/** 字母数字 */
		,
		charNum : function(value, config)
		{
			var result = "";
			var reg = /^[0-9a-zA-Z]*$/g;
			if (!reg.test(value))
			{
				result = config["label"] + "只能由字母和数字组成";
			}
			return result;
		}
		/** 字母数字下划线 */
		,
		charNumUnderline : function(value, config)
		{
			var result = "";
			var reg = /^\w+$/g;
			if (!reg.test(value))
			{
				result = config["label"] + "只能由字母，数字和下划线组成";
			}
			return result;
		}
		/** 数字 */
		,
		num : function(value, config)
		{
			var result = "";
			var reg = /^[0-9]*$/g;
			if (!reg.test(value))
			{
				result = config["label"] + "只能由数字组成";
			}
			return result;
		}
	}
	
	$.fn.extend({
		popoverBind : function(){
			$(this).on({
				focus:function(){
					$(this).popover('show');
				},
				blur:function(){
				    $(this).popover('hide');
				}
			});
		}
	});
})(jQuery);


